package com.unohacha.qqj.fzdr.main.sends;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.LabelCategaryAdapter;
import com.unohacha.qqj.fzdr.adapter.imgpicker.FabricImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.BooleanModel;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.LabelBean;
import com.unohacha.qqj.fzdr.bean.PublishTip;
import com.unohacha.qqj.fzdr.bean.citybean.ProvinceBean;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.LocationYellowSendActivity;
import com.unohacha.qqj.fzdr.ui.activity.PubSettlementActivity;
import com.unohacha.qqj.fzdr.ui.activity.supply.FabricSupplyActivity;
import com.unohacha.qqj.fzdr.util.FastUtils;
import com.unohacha.qqj.fzdr.util.GetJsonDataUtil;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.TimeUtils;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.FullyGridLayoutManager;
import com.unohacha.qqj.fzdr.view.MyGridView;
import com.unohacha.qqj.fzdr.view.citypickview.CityPickerPopWindow2;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 展会发布
 */
public class SendExhibitionActivity extends BaseActivity implements FabricImagePickerAdapter.OnRecyclerViewItemClickListener,
        OnDateSetListener, CityPickerPopWindow2.CityPickListener{
    
    @BindView(R.id.root_layout)
    LinearLayout root_layout;
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_phone_num)
    EditText etPhoneNum;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.ll_classify)
    LinearLayout llClassify;
    @BindView(R.id.tv_label_count)
    TextView tvLabelCount;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    @BindView(R.id.gv_sing_style)
    MyGridView gridView;
    @BindView(R.id.et_format)
    EditText etFormat;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.start_time)
    TextView startTime;
    @BindView(R.id.end_time)
    TextView endTime;
    @BindView(R.id.company_address)
    TextView companyAddress;
    @BindView(R.id.company_address_rl)
    RelativeLayout companyAddressRl;
    @BindView(R.id.et_extra)
    EditText etExtra;
    @BindView(R.id.et_detail_address)
    EditText etDetailAddress;
    @BindView(R.id.exhibition_introduce)
    EditText exhibitionIntroduce;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.send_btn)
    Button sendBtn;

    private LabelCategaryAdapter labelCategaryAdapter;
    private OptionsPickerView pvOptionsType;
    private String fabricName, fabricId;
    ArrayList<CatData.Two> listsDetial;
    ArrayList<PublishTip> listsCateName;
    ArrayList<LabelBean> listLabel;
    List<CatData> listTwo;
    HashMap<String, String> map;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private FabricImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数
    private String mainId = "";

    private String[] mTitles;//标题的提示的数组
    private String[] mSpecs;//规格的提示数组
    private String[] mContents;//其他内容提示数组
    private String[] mNumberss;//产品数量的数组
    private String[] mNumUnits;//数量单位的数组
    private String[] mOnePrices;//单价提示的数组
    private String[] mOnePriceUnits;//单价单位的数组
    private int type = 1;//1供应 2 需求
    long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    private TimePickerDialog mDialogYearMonthDay,mDialogYearMonthDay2;
    private int timeType ;//1.开始时间  2.结束时间

    private List<ProvinceBean> options1Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean> options2Items = new ArrayList<>();
    private List<ProvinceBean.TwoRegBean.ThreeRegBean> options3Items = new ArrayList<>();
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private Thread thread;
    private boolean isLoaded = false;
    private String province, city, district;
    private String  provinceId = "1";// 省id
    private String cityId = "2";//市 id
    private String distristId = "3";//区id
    String s;
    private int app_cate_id;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_send_exhibition;
    }

    @Override
    protected void initView() {
        commonRightImage.setVisibility(View.INVISIBLE);
        commonTitle.setText("展会发布");
        map = new HashMap<>();
        mainId = getIntent().getStringExtra("main_id");
        type = getIntent().getIntExtra("type", 0);
        fabricName = getIntent().getStringExtra("name");
        fabricId = getIntent().getStringExtra("id");
        app_cate_id = getIntent().getIntExtra("app_cate_id", 0);
        tvType.setText(fabricName);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        listTwo = new ArrayList<>();
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new FabricImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);

        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);
        pvOptionsType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(listsDetial.get(options1).getName());
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                labelCategaryAdapter.chiceState(position);
                tvLabelCount.setText(labelCategaryAdapter.getSelectCount() + "个");
            }
        });

        //日期选择
        mDialogYearMonthDay = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId("")
                .setThemeColor(getResources().getColor(R.color.timepicker_dialog_bg))
                .setCallBack(this)
                .build();
        
        getLabelData();
        getTips();
    }

    @OnClick({ R.id.send_btn, R.id.common_back, 
            R.id.start_time, R.id.end_time,R.id.company_address,R.id.company_address_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start_time://展会开始时间弹窗
                timeType = 1;
                mDialogYearMonthDay.show(getSupportFragmentManager(), "year_month_day");
                break;
            case R.id.send_btn:
               if (!FastUtils.isFastDoubleClick()){
                   if (checkIsEmpty()){
                       mSubmit();
                       //发布
                       Log.d("releaseZHInfo","startTime:"+ TimeUtils.getTimeToStamp(startTime.getText().toString())+" "+"endTime:"+TimeUtils.getTimeToStamp(endTime.getText().toString())
                       +provinceId+" "+cityId+" "+distristId);
                       
                   }
               }
                
                break;
            case R.id.common_back:
                finish();
                break;
            case R.id.company_address://展出地区位置选择
                 
                break;
            case R.id.end_time://结束时间的弹窗
                timeType = 2;
                mDialogYearMonthDay.show(getSupportFragmentManager(), "year_month");
//                showJobPickciew(mOnePriceUnits, 2);
                break;
            case R.id.company_address_rl://地区选择
                if (0 != options1Items.size()){
                    if (!FastUtils.isFastDoubleClick()) {
                        //判断软键盘是否打开，为true则关闭，否则不处理
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        boolean isOpen = imm.isActive();
                        if (isOpen) {
                            closrKeyboard();
                        }
                        provinceId = "1";// 省id
                        cityId = "2";//市 id
                        distristId = "3";//区id
                        //城市选择弹出框
                        CityPickerPopWindow2 mPopWindow = new CityPickerPopWindow2(this,options1Items);
                        mPopWindow.showPopupWindow(root_layout);
                        mPopWindow.setCityPickListener(this);
                    }
                }
                break;
        }
    }

    private void mSubmit(){
        HashMap<String,String> parmas=new HashMap<>();
        parmas.put("token",Prefer.getInstance().getToken());
        parmas.put("type","1");
        UploadRequest uploadRequest= SuperHttp.upload("api/filepic/filePic");
        if(images!=null){
            for (int i=0;i<images.size();i++){
                uploadRequest.addImageFile("file"+i,new File(images.get(i).path));
            }
        }
//        else {
//            ToastUtil.showCustomToast("请选择图片");
//            return;
//        }

        uploadRequest.addParams(parmas);

        showLoading();
        uploadRequest.request(new SimpleCallBack<BaseBean<List<ImgBean>>>() {
            @Override
            public void onFail(int errCode, String errMsg) {
                map.put("token",Prefer.getInstance().getToken());
                map.put("app_cate_id",app_cate_id+"");
                map.put("title",etTitle.getText().toString());
                map.put("tel",etPhoneNum.getText().toString());
//                       map.put("content_img",etKoufu.getText().toString().trim());
                map.put("proportion",etFormat.getText().toString());
                map.put("quantity",etNumber.getText().toString());
                map.put("scope",etExtra.getText().toString());
                map.put("content",exhibitionIntroduce.getText().toString());
                map.put("start_time",TimeUtils.getTimeToStamp(startTime.getText().toString())+"");
                map.put("end_time",TimeUtils.getTimeToStamp(endTime.getText().toString())+"");
                map.put("province_id",provinceId);
                map.put("city_id",cityId);
                map.put("fabuqu_id",distristId);
                map.put("address_content",etDetailAddress.getText().toString());
                map.put("release_days","");
                map.put("area_id","");
                Log.d("aaaaaa",s+"//");
                SuperHttp.post("api/myapplication/appExhibitionInformationRelease")
                        .addParams(map)
                        .request(new SimpleCallBack<BooleanModel>() {
                            @Override
                            public void onSuccess(BooleanModel data) {
                                ToastUtils.showT(data.getMsg());
                                //目前只请求下支付接口，因为发布是要付费的
                                payForPage(data.getOrder());

                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                ToastUtils.showT(errMsg);
                            }
                        });
//                ToastUtil.showCustomToast(errMsg);
                hideLoading();
            }

            @Override
            public void onSuccess(BaseBean<List<ImgBean>> data) {
                StringBuilder stringBuilder=new StringBuilder();
                for (int i=0;i<data.getData().size();i++){
                    stringBuilder.append(data.getData().get(i).getId()+",");
                }
                map.clear();
                s = stringBuilder.toString();
                Log.d("bbbbbb",s+"//");
                map.put("content_img",stringBuilder.toString());

                map.put("token",Prefer.getInstance().getToken());
                map.put("app_cate_id","62");
                map.put("title",etTitle.getText().toString());
                map.put("tel",etPhoneNum.getText().toString());
//                       map.put("content_img",etKoufu.getText().toString().trim());
                map.put("proportion",etFormat.getText().toString());
                map.put("quantity",etNumber.getText().toString());
                map.put("scope",etExtra.getText().toString());
                map.put("content",exhibitionIntroduce.getText().toString());
                map.put("start_time",TimeUtils.getTimeToStamp(startTime.getText().toString())+"");
                map.put("end_time",TimeUtils.getTimeToStamp(endTime.getText().toString())+"");
                map.put("province_id",provinceId);
                map.put("city_id",cityId);
                map.put("fabuqu_id",distristId);
                map.put("address_content",etDetailAddress.getText().toString());
                map.put("release_days","");
                map.put("area_id","");
                Log.d("aaaaaa",s+"//");
                SuperHttp.post("api/myapplication/appExhibitionInformationRelease")
                        .addParams(map)
                        .request(new SimpleCallBack<BooleanModel>() {
                            @Override
                            public void onSuccess(BooleanModel data) {
                                ToastUtils.showT(data.getMsg());
                                //目前只请求下支付接口，因为发布是要付费的
                                payForPage(data.getOrder());

                            }

                            @Override
                            public void onFail(int errCode, String errMsg) {
                                ToastUtils.showT(errMsg);
                            }
                        });
//                Intent intent=new Intent(SendExhibitionActivity.this, PubSettlementActivity.class);
//                intent.putExtra("params",map);
//                startActivity(intent);
//                finish();
//
                hideLoading();
            }
        });
    }

    //发布支付
    private void payForPage(String order){
        Map<String,Object> params = new HashMap<>();
        params.put("token",Prefer.getInstance().getToken());
        params.put("order",order);
        params.put("pay_type",1);//支付类型：1-支付宝;2-微信;3-余额;4-银联支付;5-积分支付
        XUtil.Post(UrlConfig.SUPPLY_FILE_PAY,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                finish();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    private boolean checkIsEmpty(){
        if (TextUtils.isEmpty(etTitle.getText())) {
            ToastUtil.showCustomToast("请填写展会名称");
            return false;
        }
        if (TextUtils.isEmpty(etExtra.getText())) {
            ToastUtil.showCustomToast("请介绍此次展会的展品范围!");
            return false;
        }
        if (etFormat.getText().length() == 0) {
            ToastUtil.showCustomToast("请填写展出面积!");
            return false;
        }
        if (etNumber.getText().length() == 0) {
            ToastUtil.showCustomToast("请填写展出数量!");
            return false;
        }
        if (startTime.getText().length() == 0) {
            ToastUtil.showCustomToast("请选择展出时间!");
            return false;
        }
        if (endTime.getText().length() == 0) {
            ToastUtil.showCustomToast("请选择展出时间!");
            return false;
        }
        
        if(exhibitionIntroduce.getText().length() == 0){
            ToastUtils.showT("请填写展会介绍");
            return false;
        }
        
        if(companyAddress.getText().length() == 0){
            ToastUtils.showT("请填写展出地址");
            return false;
        }
        
        if(etPhoneNum.getText().length() == 0){
            ToastUtils.showT("请填入联系方式");
            return false;
        }
        return true;
    }
    
    /**
     * 产品数量或产品单价的弹窗
     */
    private void showJobPickciew(final String[] mCateList, final int type) {
        if (mCateList.length == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < mCateList.length; i++) {
            list.add(mCateList[i]);
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置

                String companyType = mCateList[options1];
                
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.blue))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.black))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(SendExhibitionActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }

    ArrayList<ImageItem> images = null;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }

    private void getLabelData() {
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyLabelMatching")
                .addParam("supply_cate_id", mainId)
                .request(new SimpleCallBack<BaseBean<ArrayList<LabelBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<LabelBean>> data) {
                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listLabel = new ArrayList<>();
                        listLabel.addAll(data.getData());

                        labelCategaryAdapter = new LabelCategaryAdapter(SendExhibitionActivity.this, listLabel);
                        gridView.setAdapter(labelCategaryAdapter);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //获取供求默认提示
    private void getTips() {
        String token = Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyPrompt")
                .addParam("supply_cate_id", fabricId)
                .request(new SimpleCallBack<BaseBean<ArrayList<PublishTip>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<PublishTip>> data) {

                        if (data.getCode() == 0) {
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }

                        listsCateName = new ArrayList<>();
                        listsCateName.addAll(data.getData());
                        setLabelName();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //设置供求默认提示
    private void setLabelName() {
        if (0 != listsCateName.size()) {
            for (int i = 0; i < listsCateName.size(); i++) {
                if ("101".equals(listsCateName.get(i).getId())) {//规格
                    mSpecs = listsCateName.get(i).getPrompt();
                }

                if ("102".equals(listsCateName.get(i).getId())) {//补充说明
                    mContents = listsCateName.get(i).getPrompt();
                }
                if ("100".equals(listsCateName.get(i).getId())) {//单价单位
                    mOnePriceUnits = listsCateName.get(i).getPrompt();
                }
                if ("99".equals(listsCateName.get(i).getId())) {//单价的提示
                    mOnePrices = listsCateName.get(i).getPrompt();
                }

                if ("98".equals(listsCateName.get(i).getId())) {//数量单位
                    mNumUnits = listsCateName.get(i).getPrompt();
                }
                if ("97".equals(listsCateName.get(i).getId())) {//数量
                    mNumberss = listsCateName.get(i).getPrompt();
                }
                if ("96".equals(listsCateName.get(i).getId())) {//标题
                    mTitles = listsCateName.get(i).getPrompt();
                }
            }

            etTitle.setHint(mTitles[0]);
            etFormat.setHint(mSpecs[0]);
            etNumber.setHint(mNumberss[0]);
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        String text = getDateToString(millseconds);
        if(timeType == 1){
            startTime.setText(text);
        }else if(timeType == 2){
            endTime.setText(text);
        }
        
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }


    private void initJsonData(Context context) {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(context, "region.json");//获取assets目录下的json文件数据

        ArrayList<ProvinceBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            List<ProvinceBean.TwoRegBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            List<ProvinceBean.TwoRegBean.ThreeRegBean> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getTwo_reg().size(); c++) {//遍历该省份的所有城市
                CityList.add(jsonBean.get(i).getTwo_reg().get(c));//添加城市
                List<ProvinceBean.TwoRegBean.ThreeRegBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (null == jsonBean.get(i).getTwo_reg().get(c).getThree_reg()
                        || jsonBean.get(i).getTwo_reg().get(c).getThree_reg().size() == 0) {
                    City_AreaList.add(new ProvinceBean.TwoRegBean.ThreeRegBean());
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getTwo_reg().get(c).getThree_reg());
                }
                Province_AreaList.addAll(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.addAll(CityList);

            /**
             * 添加地区数据
             */
            options3Items.addAll( Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了

                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData(SendExhibitionActivity.this);
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    public ArrayList<ProvinceBean> parseData(String result) {//Gson 解析
        ArrayList<ProvinceBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProvinceBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProvinceBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }




    @Override
    public void pickValue(String value) {
        province = value.split("-")[0];
        city = value.split("-")[1];
        if (value.split("-").length >= 3) {
            district = value.split("-")[2];
            companyAddress.setText(province + "-" + city + "-" +district);
        }else {
            district = " ";
            companyAddress.setText(province + "-" + city);
        }

        for (int i = 0; i < options1Items.size(); i++) {
            if (province.equals(options1Items.get(i).getName())) {
                provinceId = options1Items.get(i).getId() + "";
            }
        }

        for (int i = 0; i < options2Items.size(); i++) {
            if ((options2Items.get(i).getName().contains(city))){
                cityId = options2Items.get(i).getId() + "";
            }
        }

        if (null != options3Items && 0 != options3Items.size()) {
            for (int i = 0; i < options3Items.size(); i++) {

                if (!TextUtils.isEmpty(district) && options3Items.get(i).getName().contains(district)) {
                    distristId = options3Items.get(i).getId() + "";
                }
            }
        }else {
            distristId = " ";
        }

        Log.e("TAGPROVINCE_ID", provinceId + ":" + cityId + ":" + distristId);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
    
    
    
}
